package com.sunray.cmd;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;

public class TestCmd {
   static ExecutorService service = Executors.newCachedThreadPool();

    public static void main(String[] args) throws IOException, InterruptedException {
        Process process = Runtime.getRuntime().exec(args);
        AtomicReference<String> result=new AtomicReference<>();
        AtomicReference<String> err=new AtomicReference<>();
        CountDownLatch latch=new CountDownLatch(2);
        readAllMsg(process,msg->{
            System.out.println("cmd return:\n"+msg);
            result.set(msg);
            latch.countDown();
        });
        readAllErr(process,msg->{
            System.out.println("err return:\n"+msg);
            err.set(msg);
            latch.countDown();
        });

//        process.waitFor();
        latch.await();
        System.out.println(result.get());
        System.out.println(err.get());

        System.exit(0);
    }

    private static void readAllMsg(Process process, Consumer<String> consumer) {
        BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
        readStream(process, consumer, br);
    }
    private static void readAllErr(Process process, Consumer<String> consumer) {
        BufferedReader br = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        readStream(process, consumer, br);
    }

    private static void readStream(Process process, Consumer<String> consumer, BufferedReader br) {
        service.submit(()->{
            String msg="";
            while (true){
                try {
                    if (!(process.isAlive()||br.ready())) break;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    while (br.ready()) {
                        msg+=br.readLine()+"\n";
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            consumer.accept(msg);
        });
    }
}
